package com.xxx.chat.server;

import com.xxx.chat.protocol.MessageCodecSharable;
import com.xxx.chat.protocol.ProcotolFrameDecoder;
import com.xxx.chat.server.handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 聊天室：server端
 */
@Slf4j
public class ChatServer {

    public static void main(String[] args) {
        // NioEventLoopGroup：boss负责accept()事件，worker负责io事件
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        // 提取@Sharable无状态Handler
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);    // 日志handler
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();        // 无状态的消息编码和解码器
        LoginRequestMessageHandler LOGIN_HANDLER = new LoginRequestMessageHandler();    // 登录请求消息handler
        ChatRequestMessageHandler CHAT_HANDLER = new ChatRequestMessageHandler();       // 聊天请求消息handler
        GroupCreateRequestMessageHandler GROUP_CREATE_HANDLER = new GroupCreateRequestMessageHandler();     // 创建群组请求消息handler
        GroupJoinRequestMessageHandler GROUP_JOIN_HANDLER = new GroupJoinRequestMessageHandler();           // 加入群组请求消息handler
        GroupMembersRequestMessageHandler GROUP_MEMBERS_HANDLER = new GroupMembersRequestMessageHandler();  // 获取群组成员请求消息handler
        GroupQuitRequestMessageHandler GROUP_QUIT_HANDLER = new GroupQuitRequestMessageHandler();       // 退出群组请求消息handler
        GroupChatRequestMessageHandler GROUP_CHAT_HANDLER = new GroupChatRequestMessageHandler();       // 群聊请求消息handler
        QuitHandler QUIT_HANDLER = new QuitHandler();   // 退出聊天室handler

        final int READ_IDLE_SECONDS = 50;   // 读空闲时长
        final int WRITE_IDLE_SECONDS = 0;   // 写空闲时长
        final int ALL_IDLE_SECONDS = 0;   // 读写空闲时长

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(boss, worker);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProcotolFrameDecoder());  // 自定义协议帧解码器（有状态，解决半包和粘包）
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    // 用来判断是不是 读空闲时间过长，或 写空闲时间过长
                    // 5s 内如果没有收到 channel 的数据，会触发一个 IdleState#READER_IDLE 事件
                    // 说明：IdleStateHandler是netty提供的空闲状态处理器
                    // readerIdleTime：多长时间没有读，就会发送一个心跳检测包检测是否连接
                    // writerIdleTime：多长时间没有写，就会发送一个心跳检测包检测是否连接
                    // allIdleTime：多长时间既没有读也没有写，就会发送一个心跳检测包检测是否连接
                    ch.pipeline().addLast(new IdleStateHandler(READ_IDLE_SECONDS, WRITE_IDLE_SECONDS, ALL_IDLE_SECONDS));
                    // ChannelDuplexHandler 可以同时作为入站和出站处理器
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        // 用来触发特殊事件
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception{
                            IdleStateEvent event = (IdleStateEvent) evt;
                            // 触发了读空闲事件
                            if (event.state() == IdleState.READER_IDLE) {
                                log.debug("已经 " + READ_IDLE_SECONDS + "s 没有读到数据了");
                                ctx.channel().close();
                            }
                        }
                    });
                    ch.pipeline().addLast(LOGIN_HANDLER);
                    ch.pipeline().addLast(CHAT_HANDLER);
                    ch.pipeline().addLast(GROUP_CREATE_HANDLER);
                    ch.pipeline().addLast(GROUP_JOIN_HANDLER);
                    ch.pipeline().addLast(GROUP_MEMBERS_HANDLER);
                    ch.pipeline().addLast(GROUP_QUIT_HANDLER);
                    ch.pipeline().addLast(GROUP_CHAT_HANDLER);
                    ch.pipeline().addLast(QUIT_HANDLER);
                }
            });
            Channel channel = serverBootstrap.bind(8080).sync().channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("server error", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

}
